package com.zyl.blog.common.strategy;

import com.zyl.blog.common.annotation.Sensitive;

/**
 * 邮箱脱敏策略
 * 保留首位和@后的域名，中间用*代替
 * 示例：f***@qq.com
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.common.strategy
 * @ClassName: EmailSensitiveStrategy
 * @Author FinalFantasy
 * @Date 2025/9/8-10:30
 */
public class EmailSensitiveStrategy extends AbstractSensitiveStrategy {

    @Override
    public String desensitize(String value, Sensitive annotation) {
        if (value == null || !value.contains("@")) {
            return value;
        }

        // 分割邮箱为用户名和域名
        String[] parts = value.split("@");
        if (parts.length != 2) {
            return value;
        }

        String username = parts[0];
        String domain = parts[1];

        // 如果用户名长度为1，则不脱敏
        if (username.length() <= 1) {
            return value;
        }

        // 保留用户名首位，其余用*代替
        String maskedUsername = username.charAt(0) +
                repeat(annotation.maskChar(), username.length() - 1);

        return maskedUsername + "@" + domain;
    }

    private String repeat(char c, int times) {
        if (times <= 0) {
            return "";
        }
        return String.valueOf(c).repeat(times);
    }
}
